from django.http import JsonResponse
from web.models import PlatformInfo, PlatformUser
from django import forms
from django.forms.models import model_to_dict
from web.apis.PlatformInfo.PlatformUser.v1.jwt_code import JwtCode
from web.apis import tools
from urllib.parse import quote_plus
from django.shortcuts import redirect
import requests
import time
import re

"""
错误码:
0: 成功
1: 失败
2: 参数错误
3: 请求方式错误
4: 安全验证失败
5: 权限不足
"""

key = 'BlackWidowToken'
jwt_code = JwtCode()

# 平台用户表单
class PlatformUserForm(forms.ModelForm):
    class Meta:
        model = PlatformUser
        fields = [
            'account',
            'platform',
            'password',
            'avatar',
        ]

    def clean_password(self):
        password = self.cleaned_data.get('password')
        if len(password) < 6:
            raise forms.ValidationError('密码长度不能小于6位')
        if not re.match(r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$', password):
            raise forms.ValidationError('密码必须包含字母和数字')
        return password

    def clean_account(self):
        account = self.cleaned_data.get('account')
        if len(account) < 4:
            raise forms.ValidationError('账号长度不能小于4位')
        return account

# 只返回 user_id, token
def model_to_dict_with_user_id_and_token(model):
    return {
        'user_id': model.user_id,
        'token': model.token,
    }

def model_to_dict_with_url(model):
    model_dict = model_to_dict(model)
    
    if model.avatar:
        model_dict['avatar'] = model.avatar.url
    else:
        model_dict['avatar'] = ""
    model_dict['platform'] = model.platform.name
    model_dict['create_time'] = model.create_time.strftime('%Y-%m-%d %H:%M:%S')
    model_dict['update_time'] = model.update_time.strftime('%Y-%m-%d %H:%M:%S')

    del model_dict['password']

    if model.token:
        model_dict['token'] = model.token
    else:
        secret_key = f"{model.platform.platform_id}{model.user_id}"
        token = jwt_code.generate_token(secret_key, {"user_id": model.user_id}, exp=3200)
        model_dict['token'] = token
        model.token = token
        model.save()

    return model_dict

# 验证通知服务器url
def verify_platform_info_msg_url(platform_info_msg_url):
    if not platform_info_msg_url:
        return False, '通知URL不能为空'
    if not tools.is_valid_url(platform_info_msg_url):
        return False, '通知URL格式不正确'
    return True, ''

# 向平台发送通知
def send_platform_info_msg(platform_info_msg_url, data):
    try:
        response = requests.post(
            url=platform_info_msg_url,
            json=data, 
            headers={'Content-Type': 'application/x-www-form-urlencoded'},
        )
        print(response.text)
        return response.status_code == 200
    except requests.Timeout:
        return False
    except Exception:
        return False

# 更新用户token
def update_user_token(user_id, password):
    if not user_id or not password:
        return {
            'code': 2,
            'message': '用户ID和密码不能为空',
        }
    
    platform_user = PlatformUser.objects.filter(user_id=user_id, password=password).first()
    if not platform_user:
        return {
            'code': 1,
            'message': '平台用户不存在',
        }
    
    platform_user.token = ""
    platform_user.save()
    return {
        'code': 0,
        'message': 'Token更新成功',
        'data': model_to_dict_with_url(platform_user),
    }

# 更新用户token_v1
def update_user_token_v1(user_model):
    user_model.token = ""
    user_model.save()
    return {
        'code': 0,
        'message': 'Token更新成功',
        'data': model_to_dict_with_url(user_model),
    }




# 更新Token
def update_token(request):
    if request.method != 'POST':
        return JsonResponse({
            'code': 3,
            'message': '请使用POST方法请求',
        })

    user_id = request.POST.get('user_id')
    platform_id = request.POST.get('platform_id')
    token = request.headers.get('Authorization')

    if not all([user_id, platform_id, token]):
        return JsonResponse({
            'code': 2,
            'message': '请提供完整的用户ID、平台ID和Token',
        })

    try:
        user_id_from_token = jwt_code.decode_token(platform_id + user_id, token)
        if user_id_from_token['code'] == 1:
            response = update_user_token(user_id, platform_id)
            return JsonResponse({
                'code': 0,
                'message': 'Token更新成功',
                'data': {
                    'user_id': response['data']['user_id'],
                    'token': response['data']['token'],
                },
            })
        elif user_id_from_token['code'] == 0:
            return JsonResponse({
                'code': 1,
                'message': '当前Token尚未过期，无需更新',
            })
    except Exception as e:
        return JsonResponse({
            'code': 4,
            'message': 'Token验证失败，请重新登录',
        })

# 创建平台用户
def create_platform_user(request):
    if request.method != 'POST':
        return JsonResponse({
            'code': 3,
            'message': '请使用POST方法请求',
        })

    try:
        form = PlatformUserForm(request.POST, request.FILES)
        if not form.is_valid():
            error_msg = tools.get_first_error(form)
            return JsonResponse({
                'code': 2,
                'message': error_msg,
            })

        platform_info_msg_url = request.POST.get('platform_info_msg_url')
        platform_set_token_url = request.POST.get('platform_set_token_url')
        platform_info_params = request.POST.get('platform_info_params')

        is_valid, msg = verify_platform_info_msg_url(platform_info_msg_url)
        if not is_valid:
            return JsonResponse({
                'code': 2,
                'message': msg,
            })

        platform_user = form.save()
        new_platform_user = model_to_dict_with_url(platform_user)
        # 发送通知
        notification_data = {
            'code': 0,
            'message': '平台用户创建成功',
            'data': {
                "user_id": new_platform_user['user_id'],
                "token": new_platform_user['token'],
                "platform_info_params": platform_info_params
            },
            'type': '0',
        }

        send_platform_info_msg(platform_info_msg_url, notification_data)

        if platform_set_token_url:
            return JsonResponse({
                'code': 0,
                'message': '平台用户创建成功',
                'data': {
                    'responseURL': f"{platform_set_token_url}?{key}={new_platform_user['token']}",
                },
            })

        return JsonResponse({
            'code': 0,
            'message': '平台用户创建成功',
            'data': new_platform_user,
        })

    except Exception as e:
        return JsonResponse({
            'code': 1,
            'message': '创建平台用户失败，请稍后重试',
        })

# 获取平台用户
def get_platform_user(request):
    if request.method != 'POST':
        return JsonResponse({
            'code': 3,
            'message': '请使用POST方法请求',
        })

    user_id = request.POST.get('user_id')
    platform_id = request.POST.get('platform_id')

    if not all([user_id, platform_id]):
        return JsonResponse({
            'code': 2,
            'message': '请提供用户ID和平台ID',
        })

    try:
        platform_user = PlatformUser.objects.filter(user_id=user_id, platform_id=platform_id).first()
        if not platform_user:
            return JsonResponse({
                'code': 1,
                'message': '未找到该平台用户',
            })

        return JsonResponse({
            'code': 0,
            'message': '获取平台用户成功',
            'data': model_to_dict_with_url(platform_user),
        })

    except Exception:
        return JsonResponse({
            'code': 1,
            'message': '获取平台用户失败，请稍后重试',
        })

# 更新平台用户
def update_platform_user(request):
    if request.method != 'POST':
        return JsonResponse({
            'code': 3,
            'message': '请使用POST方法请求',
        })

    user_id = request.POST.get('user_id')
    platform_id = request.POST.get('platform')

    if not all([user_id, platform_id]):
        return JsonResponse({
            'code': 2,
            'message': '请提供用户ID和平台ID',
        })

    try:
        platform_user = PlatformUser.objects.filter(user_id=user_id, platform_id=platform_id).first()
        if not platform_user:
            return JsonResponse({
                'code': 1,
                'message': '未找到该平台用户',
            })

        form = PlatformUserForm(request.POST, request.FILES, instance=platform_user)
        if not form.is_valid():
            error_msg = tools.get_first_error(form)
            return JsonResponse({
                'code': 2,
                'message': error_msg,
            })

        updated_user = form.save()
        return JsonResponse({
            'code': 0,
            'message': '平台用户更新成功',
            'data': model_to_dict_with_url(updated_user),
        })

    except Exception:
        return JsonResponse({
            'code': 1,
            'message': '更新平台用户失败，请稍后重试',
        })

# 删除平台用户
def delete_platform_user(request):
    if request.method != 'POST':
        return JsonResponse({
            'code': 3,
            'message': '请使用POST方法请求',
        })

    user_id = request.POST.get('user_id')
    platform_id = request.POST.get('platform')

    if not all([user_id, platform_id]):
        return JsonResponse({
            'code': 2,
            'message': '请提供用户ID和平台ID',
        })

    try:
        platform_user = PlatformUser.objects.filter(user_id=user_id, platform_id=platform_id).first()
        if not platform_user:
            return JsonResponse({
                'code': 1,
                'message': '未找到该平台用户',
            })

        if platform_user.avatar:
            platform_user.avatar.delete()
        platform_user.delete()

        return JsonResponse({
            'code': 0,
            'message': '平台用户删除成功',
        })

    except Exception:
        return JsonResponse({
            'code': 1,
            'message': '删除平台用户失败，请稍后重试',
        })

# 通过账号、密码查询,适用于用户登录
def get_platform_user_by_account_and_password(request):
    if request.method != 'POST':
        return JsonResponse({
            'code': 3,
            'message': '请使用POST方法请求',
        })

    account = request.POST.get('account')
    password = request.POST.get('password')
    platform = request.POST.get('platform')
    platform_set_token_url = request.POST.get('platform_set_token_url')
    platform_info_msg_url = request.POST.get('platform_info_msg_url')

    if not all([account, password, platform]):
        return JsonResponse({
            'code': 2,
            'message': '请提供账号、密码和平台信息',
        })

    is_valid, msg = verify_platform_info_msg_url(platform_info_msg_url)
    if not is_valid:
        return JsonResponse({
            'code': 2,
            'message': msg,
        })

    try:
        platform_user = PlatformUser.objects.filter(account=account, password=password).first()
        if not platform_user:
            return JsonResponse({
                'code': 1,
                'message': '账号或密码错误',
            })

        response = update_user_token(platform_user.user_id, password)
        if response['code'] != 0:
            return JsonResponse(response)

        user_data = model_to_dict_with_user_id_and_token(platform_user)

        if not send_platform_info_msg(platform_info_msg_url, {
            'code': 0,
            'message': '平台用户查询成功',
            'data': user_data,
        }):
            return JsonResponse({
                'code': 1,
                'message': '登录成功，但通知发送失败',
                'data': user_data,
            })

        if platform_set_token_url:
            return JsonResponse({
                'code': 0,
                'message': '登录成功',
                'data': {
                    'responseURL': f"{platform_set_token_url}?{key}={user_data['token']}",
                },
            })

        return JsonResponse({
            'code': 0,
            'message': '登录成功',
            'data': user_data,
        })

    except Exception:
        return JsonResponse({
            'code': 1,
            'message': '登录失败，请稍后重试',
        })
